package com.touzi.servlets;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.touzi.alipay.DingdanCanshu;
import com.touzi.alipay.ZhuanZCanshu;
import com.touzi.beans.dbs.chanpin.Chanpin;
import com.touzi.beans.dbs.dingdan.NewDingdan;
import com.touzi.beans.dbs.liushui.NewLiushui;
import com.touzi.beans.dbs.tixian.NewTixian;
import com.touzi.beans.dbs.users.ChangeKeyong;
import com.touzi.beans.dbs.users.NewUser;
import com.touzi.beans.dbs.users.User;
import com.touzi.constants.DbCons;
import com.touzi.constants.MobileCons;
import com.touzi.mapper.*;
import com.touzi.proconfig.AliConfig;
import com.touzi.proconfig.ProjectConfig;
import com.touzi.utils.BeanUtils;
import com.touzi.utils.MyHTTPUtils;
import com.touzi.utils.Yanzhengma;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "MobileServlets")
public class MobileServlets extends BaseServlet {
    private static String CLASS_NAME = "com.touzi.servlets.MobileServlets";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if (method == null) {
            response.sendRedirect("/mobile/index.html");
            return;
        }

        switch (method) {
            case "regNew":
                regNew(request, response);
                break;
            case "login":
                doLogin(request, response);
                break;
            case "verifylogin":
                verifyLogin(request, response);
                break;
            case "dotixian":
                doTixian(request, response);
                break;
            case "xiugaimmhezfb":
                xgMmZfb(request, response);
                break;
            case "verifytixian":
                verifyTixian(request, response);
                break;
            case "verifyregnew":
                verifyRegnew(request, response);
                break;
        }
    }

    private void verifyRegnew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (isRegnewParaOk(request, response)) {
            response.getWriter().print("ok");
        } else {
            response.getWriter().print("error");
        }
    }

    private boolean isRegnewParaOk(HttpServletRequest request, HttpServletResponse response) {
        String dianhua = request.getParameter("phonenum");
        String mima = request.getParameter("passwd");
        String zhifubao = request.getParameter("alipay");
        String code = request.getParameter("code");
        String tuijian = request.getParameter("recoid");

        boolean result = false;

        try {
            boolean dianhuaok = (dianhua.length() == 11) && isUserOK(dianhua);
            boolean mimaok = mima.length() >= 6;
            boolean codeok = isCodeOK(request);
            boolean tuijianok = true;
            boolean zhifbok = zhifubao.length() > 3;

            logger.debug("" + dianhuaok + mimaok + codeok + tuijianok + zhifbok + "");
            if (dianhuaok && mimaok && codeok && tuijianok && zhifbok) {
                result = true;
            }
        } catch (Exception e) {
            result = false;
        }

        return result;
    }

    //修改密码和支付宝
    private void xgMmZfb(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        try {
            String oripass = request.getParameter("origpasswd");
            String newpass = request.getParameter("newpasswd");
            String newzfb = request.getParameter("newaliaccount");
            String dianhua = request.getParameter("dianhua");

            //验证原来的密码和账号
            Map<String, String> map = new HashMap<>();
            map.put("dianhua", dianhua);
            map.put("mima", oripass);
            User user = userMapper.findUserByPhonePasswd(map);
            if (user == null) {
                sqlSession.close();
                String msg = "修改失败，请检查输入是否有误!";
                response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
                return;
            }

            Map<String, String> para = new HashMap<>();
            para.put("mima", newpass);
            para.put("zhifubao", newzfb);
            para.put("dianhua", dianhua);
            userMapper.xgMmZfbByDh(para);
            sqlSession.commit();

            Cookie usercookie = MyHTTPUtils.getCookieByName(request, MobileCons.COOKIE_USERNAME);
            usercookie.setMaxAge(0);
            response.addCookie(usercookie);
            String msg = "恭喜你修改成功!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            return;
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();

            String msg = "修改失败，请检查输入是否有误!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            return;
        } finally {
            sqlSession.close();
        }
    }

    private void verifyTixian(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        boolean userok = isLoginOk(request);
        boolean codeok = isCodeOK(request);

        if (userok && codeok) {
            response.getWriter().print("ok");
        } else {
            String result = "提示:";
            if (!userok) {
                result += " 用户与密码不匹配";
            }

            if (!codeok) {
                result += " 验证码错误";
            }
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(result);
        }
    }

    private void doTixian(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        SysconfigMapper sysconfigMapper = sqlSession.getMapper(SysconfigMapper.class);

        String dianhua = request.getParameter("user");
        String mima = request.getParameter("passwd");
        String zhifubao = request.getParameter("aliaccount");
        String jiner = request.getParameter("money");
        String canTixian = sysconfigMapper.findConfBykey("cantixian"); //全局的是否可提现配置

        if (!canTixian.equals("yes")) {
            String msg = "账户存在异常，已被系统冻结，请联系客服!!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            sqlSession.close();
            return;
        }

        boolean codeok = isCodeOK(request);
//        System.out.println(dianhua + " " + mima + " " + jiner + " " + zhifubao + " ");
        if (dianhua.equals("") || mima.equals("") || zhifubao.equals("") || jiner.equals("") || (!codeok)) {
            String msg = "输入的数据有误，请重新检查!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            return;
        }

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //验证用户名和密码
        Map<String, String> userpara = new HashMap<>();
        userpara.put("dianhua", dianhua);
        userpara.put("mima", mima);
        User user = userMapper.findUserByPhonePasswd(userpara);
        if (user == null) {
            sqlSession.close();
            String msg = "输入的数据有误，请重新检查!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            return;
        }
        //如果用户被冻结则直接返回
        if (user.frozen.equals("yes")) {
            String msg = "账户存在异常，已被系统冻结，请联系客服!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            return;
        }
        //验证账户可以用金钱和提款
        try {
            float keyong = Float.parseFloat(user.keyong);
            float tikuan = Float.parseFloat(jiner);
            if (tikuan < 1 || tikuan > keyong) {
                sqlSession.close();
                String msg = "输入的数据有误，请重新检查!";
                response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
                return;
            }
        } catch (Exception e) {
            sqlSession.close();
            String msg = "输入的数据有误，请重新检查!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            e.printStackTrace();
            return;
        }

        //全部校验通过，进行提款操作
        String appid = sysconfigMapper.findConfBykey("APPID");
        String app_private_key = sysconfigMapper.findConfBykey("APP_PRIVATE_KEY");
        String alipay_public_key = sysconfigMapper.findConfBykey("ALIPAY_PUBLIC_KEY");
        String ali_noty = sysconfigMapper.findConfBykey("ALI_NOTY");

        AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.ALI_URL,
                appid, app_private_key, AliConfig.PARA_TYPE,
                AliConfig.CHARSET, alipay_public_key, AliConfig.SIGNTYPE);
        AlipayFundTransToaccountTransferRequest alrequest = new AlipayFundTransToaccountTransferRequest();
        //提现订单号，以10开头
        String dingdan = "10" + System.currentTimeMillis() + user.id;
        ZhuanZCanshu zhuanZCanshu = new ZhuanZCanshu(dingdan, zhifubao, jiner);
        alrequest.setBizContent(BeanUtils.serializeBean(zhuanZCanshu));
        AlipayFundTransToaccountTransferResponse alresponse;
        try {
            alresponse = alipayClient.execute(alrequest);
        } catch (AlipayApiException e) {
            sqlSession.close();
            String msg = "与支付宝通信出错，请检查输入内容或者联系客服!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            e.printStackTrace();
            return;
        }
        if (alresponse.isSuccess()) {
            TixianMapper tixianMapper = sqlSession.getMapper(TixianMapper.class);
            NewTixian tixian = new NewTixian(user.id, dingdan, Float.parseFloat(jiner));
            tixianMapper.insertANewReco(tixian);

            LiushuiMapper liushuiMapper = sqlSession.getMapper(LiushuiMapper.class);
            NewLiushui liushui = new NewLiushui(user.id, Float.parseFloat(jiner), "申请提现", Integer.parseInt(user.tuijianren));
            liushuiMapper.insertANewReco(liushui);

            ChangeKeyong changeKeyong = new ChangeKeyong(user.dianhua, Float.parseFloat(jiner));
            userMapper.jianKeyong(changeKeyong);

            sqlSession.commit();
            sqlSession.close();
            String msg = "提款成功";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
        } else {
            sqlSession.close();
            String msg = "出错了，请检查输入内容或者联系客服!";
            response.sendRedirect("/msg.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
            return;
        }

    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        boolean user = isLoginOk(request);
        boolean code = isCodeOK(request);

        if (user && code) {
            String dianhua = request.getParameter("phone");
            SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = userMapper.findUserByDianhua(dianhua);
            sqlSession.close();
            User u = users.get(0);

            Cookie cookie = new Cookie(MobileCons.COOKIE_USERNAME, u.dianhuamiwen);
            cookie.setMaxAge(60 * 60 * 24 * 3);//3days
            cookie.setPath("/");
            response.addCookie(cookie);
            response.sendRedirect("/mobile");
        } else {
            request.setAttribute("msg", "参数错误！");
            request.getRequestDispatcher("WEB-INF/jsp/mobiles/commonmsg.jsp").forward(request, response);
            return;
        }
    }


    private void verifyLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        boolean user = isLoginOk(request);
        boolean code = isCodeOK(request);

        if (user && code) {
            response.getWriter().print("ok");
        } else {
            String result = "登陆提示:";
            if (!user) {
                result += " 用户与密码不匹配";
            }

            if (!code) {
                result += " 验证码错误";
            }
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(result);
        }
    }

    private boolean isLoginOk(HttpServletRequest request) {
        try {
            SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            String dianhua = request.getParameter("phone");
            String mima = request.getParameter("passwd");

            Map<String, String> map = new HashMap<>();
            map.put("dianhua", dianhua);
            map.put("mima", mima);
            User user = mapper.findUserByPhonePasswd(map);
            sqlSession.close();

            logger.debug(dianhua);
            if (user == null) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void regNew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        logger.info("通过验证，开始注册");
        boolean paraok = isRegnewParaOk(request, response);
        //如果参数错误，返回 出现这种情况一般是代码注入引起的，因为前端页面已经检查过参数了
        if (!paraok) {
            response.getWriter().print("error");
        }

        String dianhua = request.getParameter("phonenum");
        String mima = request.getParameter("passwd");
        String zhifubao = request.getParameter("alipay");
        String tuijianren = request.getParameter("recoid");
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        if (isUserOK(dianhua) && isCodeOK(request)) {
            int tuijianrenID = 0;
            try {
                tuijianrenID = Integer.parseInt(tuijianren);
            } catch (Exception e) {
                tuijianrenID = 0;
            }

            NewUser newUser = new NewUser(dianhua, mima, zhifubao, "", tuijianrenID);
            int i = mapper.regNew(newUser);
            sqlSession.commit();
            List<User> u = mapper.findUserByDianhua(dianhua);
            sqlSession.close();

            response.sendRedirect("/mobile/regmsg.jsp?result=ok&uid=" + u.get(0).getId()
                    + "&dianhua=" + u.get(0).getDianhua() + "&passwd=" + mima);
            return;
        } else {
            response.sendRedirect("/mobile/regmsg.jsp?result=error");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");

        if (method == null) {
            method = " ";
        }

        switch (method) {
            case "gomobilepage":
                goMobilePage(request, response);
                break;
            case "getyzm":
                getYzm(request, response);
                break;
            case "isuserreged":
                verifyUserReged(request, response);
                break;
            case "verifycode":
                verifyCode(request, response);
                break;
            case "test":
                request.setAttribute("msg", "未能注册成功，请检查输入是否正确！");
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/regmsg.jsp").forward(request, response);
                break;
            case "verifytuijian":
                verifyTuijian(request, response);
                break;
            //确认购买的页面
            case "toconformbuy":
                toConformBuy(request, response);
                break;
            //开始购买
            case "tobuy":
                toBuy(request, response);
                break;
            //退出登陆
            case "exitlog":
                exitLog(request, response);
                break;
            default:
                goMobilePage(request, response);
        }
    }

    private void exitLog(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Cookie usercookie = MyHTTPUtils.getCookieByName(request, MobileCons.COOKIE_USERNAME);
        if (usercookie != null) {
            usercookie.setMaxAge(0);
            response.addCookie(usercookie);
        }
        response.sendRedirect("/mobile");
    }

    /**
     * 前往移动页面的控制器
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void goMobilePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String page = request.getParameter("page");
        Cookie usercookie = MyHTTPUtils.getCookieByName(request, MobileCons.COOKIE_USERNAME);

        if (page == null) {
            if (usercookie == null) {
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/login.jsp").forward(request, response);
                return;
            } else {
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/index.jsp").forward(request, response);
                return;
            }
        }

        //除注册和登陆页面之外都需要验证cookie，防止非法请求页面
        if (page.equals("login")) {
            request.getRequestDispatcher("WEB-INF/jsp/mobiles/login.jsp").forward(request, response);
            return;
        }

        if (page.equals("regnew")) {
            request.getRequestDispatcher("WEB-INF/jsp/mobiles/regnew.jsp").forward(request, response);
            return;
        }

        if (usercookie == null) {
            request.getRequestDispatcher("WEB-INF/jsp/mobiles/login.jsp").forward(request, response);
            return;
        } else {
            goPage(page, request, response);
        }

    }

    private void goPage(String page, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        switch (page) {
            case "login":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/login.jsp").forward(request, response);
                break;
            case "regnew":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/regnew.jsp").forward(request, response);
                break;
            case "index":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/index.jsp").forward(request, response);
                break;
            case "my":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/my.jsp").forward(request, response);
                break;
            case "tixiansq":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/tixiansq.jsp").forward(request, response);
                break;
            case "myorders":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/myorders.jsp").forward(request, response);
                break;
            case "mystreams":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/mystreams.jsp").forward(request, response);
                break;
            case "myyongjin":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/myyongjin.jsp").forward(request, response);
                break;
            case "mytuandui":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/mytuandui.jsp").forward(request, response);
                break;
            case "ddfhjh":
                request.getRequestDispatcher("WEB-INF/jsp/mobiles/dingdfhjihua.jsp").forward(request, response);
                break;
        }
    }

    /**
     * 验证用户合法性，记录订单，对接支付宝
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void toBuy(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String chanpinid = request.getParameter("chanpinid");
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        ChanpinMapper chanpinmapper = sqlSession.getMapper(ChanpinMapper.class);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        DingdanMapper dingdanMapper = sqlSession.getMapper(DingdanMapper.class);

        Chanpin chanpin = chanpinmapper.findById(Integer.parseInt(chanpinid)); //获取产品信息

        Cookie usercookie = MyHTTPUtils.getCookieByName(request, MobileCons.COOKIE_USERNAME);
        if (usercookie == null) {
            request.setAttribute("msg", "请登陆后再操作！");
            request.getRequestDispatcher("WEB-INF/jsp/mobiles/commonmsg.jsp").forward(request, response);
            return;
        }
        String userphone = usercookie.getValue();
        User user = userMapper.findUserByDhmw(userphone).get(0);

        int yonghuid = user.id;
        String dingdanhao = "" + System.currentTimeMillis() + yonghuid;
        //chanpinid
        String dingdanjiner = chanpin.jiage;

        NewDingdan newDingdan = new NewDingdan(yonghuid, dingdanhao, Integer.parseInt(chanpinid),
                Float.parseFloat(chanpin.jiage));
        dingdanMapper.insertANewReco(newDingdan);
        sqlSession.commit();

        DingdanCanshu dingdanCanshu = new DingdanCanshu(dingdanhao, chanpin.jiage, chanpin.biaoti);

        SysconfigMapper sysconfigMapper = sqlSession.getMapper(SysconfigMapper.class);
        String appid = sysconfigMapper.findConfBykey("APPID");
        String app_private_key = sysconfigMapper.findConfBykey("APP_PRIVATE_KEY");
        String alipay_public_key = sysconfigMapper.findConfBykey("ALIPAY_PUBLIC_KEY");
        String ali_noty = sysconfigMapper.findConfBykey("ALI_NOTY");
        String baseUrl=sysconfigMapper.findConfBykey("base_url");
        sqlSession.close();

        AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.ALI_URL,
                appid, app_private_key, AliConfig.PARA_TYPE,
                AliConfig.CHARSET, alipay_public_key, AliConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
        alipayTradeWapPayRequest.setReturnUrl(baseUrl + "/mobile/payresult.jsp");
        alipayTradeWapPayRequest.setNotifyUrl(ali_noty + "/ali/wibadanbg");
        alipayTradeWapPayRequest.setBizContent(BeanUtils.serializeBean(dingdanCanshu));
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayTradeWapPayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + "UTF-8");
        response.getWriter().write(form);

    }

    private void toConformBuy(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String chanpinid = request.getParameter("chanpinid");
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        ChanpinMapper mapper = sqlSession.getMapper(ChanpinMapper.class);
        Chanpin chanpin = mapper.findById(Integer.parseInt(chanpinid));
        sqlSession.close();

        request.setAttribute("chanpin", chanpin);
        request.getRequestDispatcher("WEB-INF/jsp/mobiles/querenzhifu.jsp").forward(request, response);
    }

    /**
     * 验证验证码是否正确，如果正确返回ok否则error
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (isCodeOK(request)) {
            response.getWriter().print("ok");
        } else {
            response.getWriter().print("error");
        }
    }

    private boolean isCodeOK(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            String input = request.getParameter("code");
            String code = (String) session.getAttribute("code");
            logger.debug(input + " -- " + code);

            return input.equalsIgnoreCase(code);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void getYzm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        HttpSession session = request.getSession();
        Yanzhengma vCode = new Yanzhengma(150, 40, 5, 150);
        session.setAttribute("code", vCode.getCode());
        vCode.write(response.getOutputStream());
    }

    /**
     * 如果用户没有注册返回ok,否则返回error
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void verifyUserReged(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String phone = request.getParameter("user");

        if (isUserOK(phone)) {
            response.getWriter().print("ok");
        } else {
            response.getWriter().print("error");
        }
    }

    private void verifyTuijian(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String reco = request.getParameter("reco");

        if (isTuijianOk(reco)) {
            response.getWriter().print("ok");
        } else {
            response.getWriter().print("error");
        }
    }

    /**
     * 用户是否注册，判断工具
     *
     * @param phone
     * @return
     */
    private boolean isUserOK(String phone) {
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> u = mapper.findUserByDianhua(phone);
        sqlSession.close();
        if (u.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    private boolean isTuijianOk(String tuijian) {
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int tuijianid = 0;
        try {
            tuijianid = Integer.parseInt(tuijian);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
        User u = mapper.findUserByID(tuijianid);
        sqlSession.close();
        if (u == null) {
            return false;
        } else {
            return true;
        }
    }
}
